<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="园区名称" prop="parkName">
        <el-input
          v-model="queryParams.parkName"
          placeholder="请输入园区名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="园区标签" prop="parkTags">
        <el-select
          v-model="queryParams.parkTags"
          multiple
          filterable
          clearable
          placeholder="请选择园区标签"
          style="width: 180px"
          @change="handleQuery"
          :loading="optionsLoading"
        >
          <el-option
            v-for="item in parkTagsOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="库房类型" prop="warehouseTypes">
        <el-select
          v-model="queryParams.warehouseTypes"
          multiple
          filterable
          clearable
          placeholder="请选择库房类型"
          style="width: 180px"
          @change="handleQuery"
          :loading="optionsLoading"
        >
          <el-option
            v-for="item in warehouseTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="硬件配置" prop="hardwareConfig">
        <el-select
          v-model="queryParams.hardwareConfig"
          multiple
          filterable
          clearable
          placeholder="请选择硬件配置"
          style="width: 180px"
          @change="handleQuery"
          :loading="optionsLoading"
        >
          <el-option
            v-for="item in hardwareConfigOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="园区服务" prop="parkServices">
        <el-select
          v-model="queryParams.parkServices"
          multiple
          filterable
          clearable
          placeholder="请选择园区服务"
          style="width: 180px"
          @change="handleQuery"
          :loading="optionsLoading"
        >
          <el-option
            v-for="item in parkServiceOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="地理位置" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入地理位置"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="经度" prop="longitude">
        <el-input
          v-model="queryParams.longitude"
          placeholder="经度"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="纬度" prop="latitude">
        <el-input
          v-model="queryParams.latitude"
          placeholder="纬度"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出租单价" prop="rentalPrice">
        <el-input
          v-model="queryParams.rentalPrice"
          placeholder="请输入出租单价"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <template slot="append">元/m²</template>
        </el-input>
      </el-form-item>
      <el-form-item label="园区管理人" prop="manager">
        <el-input
          v-model="queryParams.manager"
          placeholder="请输入园区管理人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input
          v-model="queryParams.contactPhone"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 新增：是否推荐单选 -->
      <el-form-item label="是否推荐" prop="isRecommend">
        <el-select v-model="queryParams.isRecommend" placeholder="请选择推荐状态" clearable @change="handleQuery" style="width: 120px">
          <el-option label="推荐" :value="1"></el-option>
          <el-option label="不推荐" :value="0"></el-option>
          <el-option label="全部" :value="null"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:park:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:park:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:park:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:park:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="parkList" 
      @selection-change="handleSelectionChange"
      :row-style="{ height: '100px' }"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="parkId" />
      <el-table-column label="园区名称" align="center" prop="parkName" />
      <el-table-column label="园区简介" align="center" prop="parkDescription">
        <template slot-scope="scope">
          <div
            style="max-width: 200px; max-height: 100px; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical; white-space: normal; text-overflow: ellipsis;"
            :title="scope.row.parkDescription"
          >
            {{ scope.row.parkDescription }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="园区标签" align="center" prop="parkTags">
        <template slot-scope="scope">
          <span v-if="scope.row.parkTags">{{ scope.row.parkTags.map(item => item.tagName).join(',') }}</span>
          <span v-else>暂无标签</span>
        </template>
      </el-table-column>
      <el-table-column label="总面积" align="center" prop="totalArea">
        <template slot-scope="scope">
          <span>{{ scope.row.totalArea }} m²</span>
        </template>
      </el-table-column>
      <el-table-column label="建筑面积" align="center" prop="buildingArea">
        <template slot-scope="scope">
          <span>{{ scope.row.buildingArea }} m²</span>
        </template>
      </el-table-column>
      <el-table-column label="仓库类型" align="center" prop="warehouseTypes">
        <template slot-scope="scope">
          <span v-if="scope.row.warehouseTypes">{{ scope.row.warehouseTypes.map(item => item.typeName).join(',') }}</span>
          <span v-else>暂无库房类型</span>
        </template>
      </el-table-column>
      <el-table-column label="硬件配置" align="center" prop="hardwareConfig">
        <template slot-scope="scope">
          <span v-if="scope.row.hardwareConfig">{{ scope.row.hardwareConfig.map(item => item.configName).join(',') }}</span>
          <span v-else>暂无硬件配置</span>
        </template>
      </el-table-column>
      <el-table-column label="地理位置" align="center" prop="location" />
      <el-table-column label="园区服务" align="center" prop="parkServices">
        <template slot-scope="scope">
          <span v-if="scope.row.parkServices">{{ scope.row.parkServices.map(item => item.serviceName).join(',') }}</span>
          <span v-else>暂无园区服务</span>
        </template>
      </el-table-column>
      <el-table-column label="可出租面积" align="center" prop="rentedArea">
        <template slot-scope="scope">
          <span>{{ scope.row.rentedArea }} m²</span>
        </template>
      </el-table-column>
      <el-table-column label="出租单价" align="center" prop="rentalPrice">
        <template slot-scope="scope">
          <span>{{ scope.row.rentalPrice }} 元/m²</span>
        </template>
      </el-table-column>
      <el-table-column label="园区管理人" align="center" prop="manager" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" />
      <el-table-column label="缩略图" align="center" prop="thumbnailUrl" width="100">
        <template slot-scope="scope">
          <el-image 
            v-if="scope.row.thumbnailUrl"
            :src="getFullImageUrl(scope.row.thumbnailUrl)" 
            style="width: 50px; height: 50px;"
            :preview-src-list="[getFullImageUrl(scope.row.thumbnailUrl)]">
          </el-image>
          <span v-else>暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="海报图" align="center" prop="posterUrl" width="120">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.posterUrl"
            :src="getFullImageUrl(scope.row.posterUrl)"
            style="width: 80px; height: 40px;"
            :preview-src-list="[getFullImageUrl(scope.row.posterUrl)]"
          />
          <span v-else>暂无海报</span>
        </template>
      </el-table-column>
      <!-- 新增：是否推荐列，显示推荐/不推荐 -->
      <el-table-column label="是否推荐" align="center" prop="isRecommend">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isRecommend"
            :active-value="1"
            :inactive-value="0"
            @change="handleRecommendChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:park:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:park:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


  </div>
</template>

<script>
import { listPark, delPark, updatePark, updateParkRecommend } from "@/api/system/park"
import { BASE_FILE_URL, BASE_API } from '@/utils/constants'

export default {
  name: "Park",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 园区列表表格数据
      parkList: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        parkName: null,
        parkDescription: null,
        parkTags: [],
        totalArea: null,
        buildingArea: null,
        warehouseTypes: [],
        hardwareConfig: [],
        location: null,
        longitude: null,
        latitude: null,
        parkServices: [],
        rentedArea: null,
        rentalPrice: null,
        manager: null,
        contactPhone: null,
        isRecommend: null // 新增：是否推荐，搜索条件
      },



    }
  },
  created() {
    this.getList()
  },
  methods: {


    /** 拼接服务器图片地址 */
    getFullImageUrl(imageUrl) {
      if (!imageUrl) return '';
      // 如果已经是http/https/base64开头，直接返回
      if (/^(http|https):\/\//.test(imageUrl) || imageUrl.startsWith('data:image/')) {
        return imageUrl;
      }
      // 兼容斜杠
      if (imageUrl.startsWith('/')) {
        return BASE_API + imageUrl;
      }
      // 默认拼接文件服务器路径
      return BASE_FILE_URL + imageUrl;
    },
    /** 查询园区列表列表 */
    async getList() {
      this.loading = true
      // 处理多选参数为JSON字符串
      const params = { ...this.queryParams }
      // if (Array.isArray(params.parkTags)) params.parkTags = JSON.stringify(params.parkTags)
      // if (Array.isArray(params.warehouseTypes)) params.warehouseTypes = JSON.stringify(params.warehouseTypes)
      // if (Array.isArray(params.hardwareConfig)) params.hardwareConfig = JSON.stringify(params.hardwareConfig)
      // if (Array.isArray(params.parkServices)) params.parkServices = JSON.stringify(params.parkServices)
      
      try {
        const response = await listPark(params)
        this.parkList = response.rows
        this.total = response.total
        

      } catch (error) {
        console.error('获取园区列表失败:', error)
        this.$modal.msgError('获取园区列表失败')
      } finally {
        this.loading = false
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      // 新增：重置是否推荐为全部
      this.queryParams.isRecommend = null
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.parkId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push('/system/park/add')
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const parkId = row.parkId || this.ids
      this.$router.push(`/system/park/add?id=${parkId}`)
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const parkIds = row.parkId || this.ids
      this.$modal.confirm('是否确认删除园区列表编号为"' + parkIds + '"的数据项？').then(function() {
        return delPark(parkIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/park/export', {
        ...this.queryParams
      }, `park_${new Date().getTime()}.xlsx`)
    },

    // 处理推荐状态变化
    handleRecommendChange(row) {
      const parkId = row.parkId;
      const isRecommend = row.isRecommend;
      
      // 如果要设置为推荐状态，先确认
      if (isRecommend === 1) {
        this.$modal.confirm('每个区域只能有一个推荐园区，确定要设置该园区为推荐状态吗？').then(() => {
          // 用户确认后调用接口更新
          this.updateRecommendStatus(parkId, isRecommend);
        }).catch(() => {
          // 用户取消，恢复原始状态
          row.isRecommend = !isRecommend;
        });
      } else {
        // 取消推荐状态直接更新
        this.updateRecommendStatus(parkId, isRecommend);
      }
    },

    // 更新推荐状态的接口调用
    updateRecommendStatus(parkId, isRecommend) {
      updateParkRecommend(parkId, isRecommend).then(response => {
        this.$modal.msgSuccess("推荐状态更新成功");
        // 状态更新成功后刷新列表
        this.getList();
      }).catch(error => {
        this.$modal.msgError("推荐状态更新失败: " + error.message);
        // 恢复原始值
        this.getList(); // 重新获取列表数据，确保状态一致
      });
    }
  }
}
</script>


